package com.pz.gulimall.product.service.impl;

import com.pz.gulimall.common.utils.R;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

@Service
public class FileUploadService {
    private static final Logger logger = LoggerFactory.getLogger(FileUploadService.class);
    //以时间作为文件夹
    static SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd/");

    /**
     * 文件上传服务
     * @param zipFile 上传文件流
     * @param path 存储在本服务器的路径
     * @param fileName 文件名称
     * */
    public R upLoadFile(MultipartFile zipFile, String path, String fileName) {
        if(zipFile.isEmpty()){
            return R.error(500, "上传文件为空");
        }
        File targetFile = new File(path,fileName);
        try {
            FileUtils.forceMkdir(new File(path));
        } catch (IOException e) {
            e.printStackTrace();
            return R.error("创建文件夹:"+path+"失败");
        }
        FileOutputStream fileOutputStream = null;
        try {
            fileOutputStream = new FileOutputStream(targetFile);
            IOUtils.copy(zipFile.getInputStream(),fileOutputStream);
            logger.info("------>>>>>>成功上传一个文件<<<<<<------");
        } catch (IOException e) {
            e.printStackTrace();
            return R.error("IO读写错误");
        }finally {
            if(fileOutputStream!=null){
                try {
                    fileOutputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                    logger.error("输出流关闭错误",e);
                }
            }
        }
        return R.ok("上传成功");
    }

    public R uploadFile(MultipartFile zipFile, String fileName){
        String path = "D:\\tomcat-server\\"+sdf.format(new Date())+"\\";
        return upLoadFile(zipFile,path,fileName);
    }
}
